<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------


// 应用公共文件
//往管理员信息中添加权限列表，
//用户在管理员登陆或信息刷新时，根据adm_role_id获取相应的权限信息，组成完整的用户信息
function addRoleListInAdminInfo($adminInfo) {
    $adm_role_id = $adminInfo['adm_role_id'];
    $rol_list = model("CmsRole")->find($adm_role_id)['rol_list'];
    $rol_list = explode("|", $rol_list);
    //此处，已将管理员的权限列表数据转化为数组了
    $adminInfo['role_list'] = $rol_list;
    return $adminInfo;
}

//判断管理员是否登陆
function isLogin() {
    return session("?adminInfo") ? true : false;
}

//获得当前管理员的role身份信息（获得身份名称）
function getAdminRoleInfo() {
    $adminInfo = session("adminInfo");
    $adm_role_id = $adminInfo['adm_role_id'];
    $roleInfo = model("CmsRole")->find($adm_role_id);
    return $roleInfo;
}


//组装返回给layui表格的json信息
function getJson($count, $info) {
    $data = [
        "code" => 0,
        "msg" => "success",
        "count" => $count,
        "data" => $info
    ];
    return json($data);
}

//返回权限数组
function getRoleList() {
    $roleList = [
        "adminList" => "职工管理",
        "roleList" => "权限管理",
        "institutionList" => "机构列表",
        "cityList" => "城市列表",
        "articleCategoryList" => "文章分类",
        "goodArticleList"=>"好文列表",
        "goodClassList"=>"好课列表",
//地区管理、年份管理、信息管理、日志查看
    //招生信息子菜单
        "locationList"=>"地区管理",
        "yearList"=>"年份管理",
        "informationList"=>"信息管理",
        "logList"=>"日志查看",

        "carouselList"=>"轮播图",
        "recommendList"=>"平台推荐",
        "show" => "系统设置",
        "backup" => "备份管理"
    ];
    return $roleList;
}


//判断权限信息
function judgeRole($__METHOD__) {
    $methodName = explode("::", $__METHOD__)[1];
    $adminInfo = session("adminInfo");
    return in_array($methodName, $adminInfo['role_list']);
}

//前台异步获取列表信息组装
function indexGetData($page_all, $page_num, $limit, $data) {
    $page_all = (int)($page_all / $limit) + 1;
    $data = [
        "status" => 1,
        "page_all" => (int)$page_all,
        "page_num" => $page_num,
        "data" => $data
    ];
    return json($data);
}

//文章浏览量+1
function articleViewTimesAdd($articleInfo,$art_id=null) {
    $articleInfo['art_view_times'] = $articleInfo['art_view_times'] + 1;
    $articleInfo->save();
}

//培优机构浏览次数+1
function institutionViewTimesAdd($institutionInfo){
    $institutionInfo['ins_view_times']=$institutionInfo['ins_view_times']+1;
    $institutionInfo->save();
}


//图片上传处理方法
function imgUpload($file,$needCompression=-1) {
//    {"code":0,"mag":"上传成功","data":{"src":"测试","file":{"getExtension":"jpg","getSaveName":"20190912\\1ebbafd79817d0f29e0d1d7bf8db689b.jpg","getFilename":"1ebbafd79817d0f29e0d1d7bf8db689b.jpg"}}}
    $info = $file->validate([//文件大小 100万字节是约等于1M
        'ext' => 'jpeg,png,jpg,gif,webp'  //文件扩展名
    ])->move('uploads' . DS . "admin" . DS);
    $saveName = $info->getSaveName();
    //获取头像的基础路径
    $url = DS . "uploads" . DS . "admin" . DS . $saveName;

    //获得图片地址
    $source = ROOT_PATH . "public" . $url;
    //没有指定，就按照配置文件中来设置
    if($needCompression==-1){
        $needCompression = config("setting.needCompress");
    }

    if ($needCompression) {
        //对该图片进行压缩
        $Imgcompress = new \app\common\service\Imgcompress($source, 0.5);
        $result = $Imgcompress->compressImg($source);
    }
    return $url;
}

//按照“主分类，子分类”的顺序返回文章分类信息
//参数$isDecorate，表示是否在子分类前面加上修改字符串
function getSpecialOrderCategoryInfo($isDecorate = false) {
    $condition['acc_parent_id'] = ['eq', -1];
    //找到所有的一级分类
    $parentCategoryInfo = model("CmsArticleCategory")
        ->where($condition)
        //按照分类sort值进行排序
        ->order("acc_sort", "asc")
        ->select();

    //总数据
    $categoryInfo = [];
    //遍历一级标签，获取该一级标签下的二级标签
    foreach ($parentCategoryInfo as $value) {
        $categoryInfo[] = $value;
        $acc_id = $value['acc_id'];
        $childCategoryInfo = model("CmsArticleCategory")
            ->where("acc_parent_id", "=", $acc_id)
            ->order("acc_sort", "asc")
            ->select();
        foreach ($childCategoryInfo as $item) {
            $categoryInfo[] = $item;
        }
    }
    if ($isDecorate) {
        $childCategoryDecorateString = config("setting.childCategoryDecorateString");
        foreach ($categoryInfo as &$value) {
            if ($value['acc_parent_id'] != -1) {
                $value['acc_name'] = $childCategoryDecorateString . $value['acc_name'];
            }
        }
    }

    return $categoryInfo;
}

//得到好课分类id
function getGoodClassCategoryId(){
    $categoryId=config("setting.goodClassCategoryId");
    if(!$categoryId){
        $tempData=model("CmsArticleCategory")->where("acc_name","like","%好课%")->find();
        $categoryId=$tempData['acc_id'];
    }
    return $categoryId;
}

//获取“好课”分类信息
function getGoodClassCategoryInfo(){
    $info=model("CmsArticleCategory")->where("acc_id","=",getGoodClassCategoryId())->find();
    return $info;
}

//获取“好文”分类信息
function getGoodArticleCategoryInfo(){
    $info=model("CmsArticleCategory")->where("acc_id","=",getGoodArticleCategoryId())->find();
    return $info;
}



//得到好文分类id
function getGoodArticleCategoryId(){
    $categoryId=config("setting.goodArticleCategoryId");
    if(!$categoryId){
        $tempData=model("CmsArticleCategory")->where("acc_name","like","%好文%")->find();
        $categoryId=$tempData['acc_id'];
    }
    return $categoryId;
}

//返回好课子分类信息列表
function getGoodClassSubCategoryList(){
    $categoryList=model("CmsArticleCategory")->where("acc_parent_id","=",getGoodClassCategoryId())->select();
    return $categoryList;
}

//返回好课子分类的ids
function getGoodClassSubCategoryIds(){
    $ids=[];
    $list=model("CmsArticleCategory")->where("acc_parent_id","=",getGoodClassCategoryId())
        //还要查找该分类是否启用是否启用
         ->where("acc_status","=",\app\lib\enum\Status::on)
        ->select();
    foreach($list as $value){
        $ids[]=$value['acc_id'];
    }
    return $ids;
}

function getGoodClassSubCategoryIdsStr(){
    $ids="";
    $list=model("CmsArticleCategory")->where("acc_parent_id","=",getGoodClassCategoryId())
        //还要查找该分类是否启用是否启用
        ->where("acc_status","=",\app\lib\enum\Status::on)
        ->select();
    foreach($list as $value){
        $ids.=$value['acc_id'].",";
    }
    $ids=trim($ids,",");
    $ids="(".$ids.")";
    return $ids;
}


//返回好文子分类的ids
function getGoodArticleSubCategoryIds(){
    $ids=[];
    $list=model("CmsArticleCategory")->where("acc_parent_id","=",getGoodArticleCategoryId())
        //还要查找该分类是否启用是否启用
        ->where("acc_status","=",\app\lib\enum\Status::on)
        ->select();
    foreach($list as $value){
        $ids[]=$value['acc_id'];
    }
    return $ids;
}

//返回好文分类信息列表
function getGoodArticleSubCategoryList(){
    $categoryList=model("CmsArticleCategory")->where("acc_parent_id","=",getGoodArticleCategoryId())
        //还要查找该分类是否启用是否启用
        ->where("acc_status","=",\app\lib\enum\Status::on)
        ->select();
    return $categoryList;
}


//返回一级分类
function getParentCategoryInfo() {
    $categoryInfo = model("CmsArticleCategory")->where("acc_parent_id", "=", -1)->select();
    return $categoryInfo;
}


//对文章信息的处理
function handleArticleData($data) {

    //只有系统管理员，才能设定文章的状态
    //如果是机构管理员，由于没有好课状态改变权限，因此只能使用默认值
    if(!isInstitutionAdmin()){
        $data['art_istop'] = isset($data['art_istop']) && $data['art_istop'] == "on" ? \app\lib\enum\Status::on : \app\lib\enum\Status::off;
        $data['art_ishot'] = isset($data['art_ishot']) && $data['art_ishot'] == "on" ? \app\lib\enum\Status::on : \app\lib\enum\Status::off;
        $data['art_isshow'] = isset($data['art_isshow']) && $data['art_isshow'] == "on" ? \app\lib\enum\Status::on : \app\lib\enum\Status::off;
        $data['art_ischeck'] = isset($data['art_ischeck']) && $data['art_ischeck'] == "on" ? \app\lib\enum\Status::on : \app\lib\enum\Status::off;
    }

    $data['art_sort'] = isset($data['art_sort']) && $data['art_sort'] != "" ? $data['art_sort'] : 50;
    $data['art_category_id'] = isset($data['childCategory']) && $data['childCategory'] != -1 && $data['childCategory'] != "" ? $data['childCategory'] : $data['parentCategory'];

    //对关键字做逗号替换
    $data['art_keywords'] = str_replace("，", ",", $data['art_keywords']);
    $data['art_keywords'] = preg_replace("/,+/", ",", $data['art_keywords']);
    return $data;
}

//检验备份数据合法性
function checkBackupData($data) {
    $backupInfo = model("CmsDatabaseBackup")->find($data['bak_id']);
    return $backupInfo['bak_name'] === $data['bak_name'];
}

//组装层级间返回的数据
function getResultData($status, $msg, $data = []) {
    $data = [
        "status" => $status,
        "msg" => $msg,
        "data" => $data
    ];
    return $data;
}

//删除目录下的文件
function delFileUnderDir($dirName = "") {
    //使用opendir函数读取目录下的所有内容，并关闭
    if ($handle = opendir($dirName)) {
        //循环遍历文件夹下的文件
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..") {
                $filePath = $dirName . DS . $item;
                if (is_dir($filePath)) {
                    //递归删除
                    delFileUnderDir($filePath);
                    rmdir($filePath);
                } else {
                    unlink($filePath);
                }
            }
        }
        //关闭链接
        closedir($handle);
    }
}

function refreshWebInfoInCache() {
    $webInfo = model("CmsWebsite")->find();
    cache("webInfo", $webInfo);
}


//刷新session中的管理员信息
function refreshAdminInfoInSession() {
    if (session("adminInfo")) {
        $adm_id = session("adminInfo")['adm_id'];
        $newAdminInfo = model("CmsAdmin")->find($adm_id);
        $newAdminInfo = addRoleListInAdminInfo($newAdminInfo);
        session("adminInfo", $newAdminInfo);
    }
}

//获取培训机构管理员 rol_id
function getInstitutionRoleId() {
    if ($id = config("setting.roleIdOfInstitution")) {
        return $id;
    }
    $condition = [];
    $condition['rol_name'] = ['like', "%培训机构管理员%"];
    $roleInfo = model("CmsRole")->where($condition)->find();
    return $roleInfo['rol_id'];
}

//根据管理员姓名，返回管理员的id
function getAdminIdsFromAdminRealname($adm_realname) {
    $condition = [];
    $condition['adm_realname'] = ['like', "%" . $adm_realname . "%"];
    $adminList = model("CmsAdmin")->where($condition)->select();
    $finalIds = [];
    foreach ($adminList as $value) {
        $finalIds[] = $value["adm_id"];
    }
    return $finalIds;
}

//获取所有城市信息
function getCityList() {
    $cityList = model("PyCity")->select();
    return $cityList;
}

//获取文章添加时的培训机构数据
//如果是，则返回相关培训机构的信息
//如果不是，返回全部培训机构信息
function getInstitutionListToArticle() {
    //刷新用户信息
    refreshAdminInfoInSession();
    //进行判断
    $adminInfo = session("adminInfo");
    $condition = [];
    if ($adminInfo['adm_role_id'] == getInstitutionRoleId()) {
        $condition['ins_admin_id'] = ['eq', $adminInfo['adm_id']];
    }
    $institutionData = model("PyInstitution")->where($condition)->select();
    return $institutionData;
}

//判断当前的管理员是否是教育机构管理员
//如果是，返回相关教育机构信息
//如果不是，返回false
function isInstitutionAdmin() {
    //是否已经是 登陆状态
    if (session("adminInfo")) {
        refreshAdminInfoInSession();
        $adminInfo = session("adminInfo");
        if ($adminInfo['adm_role_id'] == getInstitutionRoleId()) {
            return model("PyInstitution")->where("ins_admin_id", "=", $adminInfo['adm_id'])->find();
        } else {
            return false;
        }
    } else {
        return false;
    }

}


/**
 * 函数的含义说明
 * Description of the meaning of the function
 * @access public
 * @param int $arg1 参数一的说明(Description of parameter one)
 * @param int $arg2 参数二的说明(Description of parameter one)
 * @return int 返回类型
 */
function getBiggerOne($num1,$num2){
    return $num1>$num2?$num1:$num2;
}


//传入文章的id，判断当前管理员是否能够对该文章进行编辑
function checkArticle($art_id){
    $articleInfo=model("CmsArticle")->find($art_id);
    $adminInfo=session("adminInfo");
    //只有当管理员是培训机构管理员时，才对其进行权限限制
    //系统管理员，可以修改任意文章与机构
    if($adminInfo['adm_role_id']==getInstitutionRoleId()){
        $institutionInfo=model("PyInstitution")->where("ins_admin_id","=",$adminInfo['adm_id'])->find();
        //如果这篇文章不属于该管理员所属的机构，返回false;
        if($articleInfo['art_institution_id']!=$institutionInfo['ins_id']){
            return false;
        }
    }
    return true;

}


//传入机构的id，判断当前管理员是否能够给对该机构进行编辑
function checkInstitution($ins_id){
    $adminInfo=session("adminInfo");
    $institutionInfo=model("PyInstitution")->find($ins_id);
    if($adminInfo['adm_role_id']==getInstitutionRoleId()){
        if($adminInfo['adm_id']!=$institutionInfo['ins_admin_id']){
            return false;
        }
    }
    return true;

}


//生成指定位数的随机字符串
function getRandomString($len) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $random_string = '';
    for ($i = 0; $i < $len; $i++) {
        $random_string .= $chars [mt_rand(0, strlen($chars) - 1)];
    }
    return $random_string;
}

//发送请求
function httpRequest($url,$data=[],$method="get"){
    $data  = json_encode($data,JSON_UNESCAPED_UNICODE);
    $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
    if($method=="post"){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return json_decode($output,true);
}

function getSDKParams(){
    //返回微信SDK参数
//        {
//  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//  appId: '', // 必填，公众号的唯一标识
//  timestamp: , // 必填，生成签名的时间戳
//  nonceStr: '', // 必填，生成签名的随机串
//  signature: '',// 必填，签名
//  jsApiList: [] // 必填，需要使用的JS接口列表
//}
    $SDKParams=[];
    $SDKParams["debug"]=false;
    $SDKParams['appId']=config("wechat.AppId");
    $SDKParams['timestamp']=time();
    $SDKParams['nonceStr']=getRandomString(32);
    $signature=getSignature($SDKParams);
    $SDKParams['signature']=$signature;
//    $SDKParams['jsApiList']=['getLocation',"openLocation"];
    $SDKParams['jsApiList']=["getLocation","openLocation","updateAppMessageShareData"];
    return json_encode($SDKParams,JSON_UNESCAPED_UNICODE);
}




//获取微信SDK签名
function getSignature($SDKParams){
    $jsapi_ticket=getJsApiTicket();
    $noncestr=$SDKParams['nonceStr'];
    $timestamp=$SDKParams['timestamp'];
    $url=getUrl();
    $str="jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s";
    $str=sprintf($str,$jsapi_ticket,$noncestr,$timestamp,$url);
    return sha1($str);
}

//获取access_token
//access_token信息存在cache的数据结构是
//$data=[
//    "access_token"=>"123",
//    "expire_time"=>"123"
//];
function getAccessToken(){
    $access_token=cache("access_token");
    if($access_token==""||$access_token['expire_time']<time()){
        //失效或者过期了，重新发送请求，重新获取access_token
        $url=sprintf(config("wechat.access_token_url"),config("wechat.AppId"),config("wechat.AppSecret"));
        $data=httpRequest($url);
        try{
            $access_token=$data['access_token'];
            $expire_time=(int)time()+(int)$data['expires_in']-180;
            $cacheData=[
                "access_token"=>$access_token,
                "expire_time"=>$expire_time
            ];
            cache("access_token",$cacheData);
            return $cacheData['access_token'];
        }catch (Exception $exception){
            return $data['errmsg'];
        }


    }else{
        return $access_token['access_token'];
    }
}

//获取jsapi票据
function getJsApiTicket(){
    $jsapi_ticket=cache("jsapi_ticket");
    if($jsapi_ticket==""||$jsapi_ticket['expire_time']<time()){
        //失效或者过期了，重新发送请求，重新获取jsapi_ticket
        $url=sprintf(config("wechat.jsapi_ticket_url"),getAccessToken());
        $data=httpRequest($url);
       if($data['errcode']==0){
           $jsapi_ticket=$data['ticket'];
           $expire_time=(int)time()+(int)$data['expires_in']-180;
           $cacheData=[
               "jsapi_ticket"=>$jsapi_ticket,
               "expire_time"=>$expire_time
           ];
           cache("jsapi_ticket",$cacheData);
           return $cacheData['jsapi_ticket'];
       }else{
           return $data['errmsg'];
       }
    }else{
        return $jsapi_ticket['jsapi_ticket'];
    }
}

//获取当前网页的url
function getUrl(){
    $pageURL = 'http://';
    if ($_SERVER["SERVER_PORT"] != "80")
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    }
    else
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}


//截取富文本内容
//输入富文本
//返回长度为50的字符串
function getStringFromRichText($richEext){
    $string=$richEext;
    $html_string = htmlspecialchars_decode($string);
//将空格替换成空
    $content = str_replace(" ", "", $html_string);
//函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
    $contents = strip_tags($content);

//返回字符串中的前80字符串长度的字符
    $text = mb_substr($contents, 0, 50, "utf-8");
    return $text;
}

//获取一定条件下的记录条数
function getCount($model,$condition){
    $countInfo=model($model)->field("count(*)")->where($condition)->select();
    return $countInfo[0]['count(*)'];
}

//一下是与微信交互的工具函数

//创建userInfo的session数据格式
function insertUserInfoInSession($dataArray)
{
    $userInfo = session("userInfo");
    if ($userInfo == "") {
        $userInfo = [];
    }
    isset($dataArray['code']) ? $userInfo['code'] = $dataArray['code'] : true;
    isset($dataArray['access_token']) != null ? $userInfo['access_token'] = $dataArray['access_token'] : true;
    isset($dataArray['expires_in']) != null ? $userInfo['expires_in'] = $dataArray['expires_in'] : true;
    isset($dataArray['refresh_token']) != null ? $userInfo['refresh_token'] = $dataArray['refresh_token'] : true;
    isset($dataArray['data']) != null ? $userInfo['data'] = $dataArray['data'] : true;
    session("userInfo", $userInfo);
}

//发送请求
function curl_get($url)
{
    $header = array(
        'Accept: application/json',
    );
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 超时设置,以秒为单位
    curl_setopt($curl, CURLOPT_TIMEOUT, 1);

    // 超时设置，以毫秒为单位
    // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

    // 设置请求头
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    //执行命令
    $data = curl_exec($curl);

    // 显示错误信息
    if (curl_error($curl)) {
        print "Error: " . curl_error($curl);
    } else {
        // 返回内容
        curl_close($curl);
        return json_decode($data, true);
    }
}

function getCurrentUrl()
{
    $pageURL = 'http://';
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}


